﻿var isTop = true;

try {
    isTop =
        (document.location.href.match(/getpocket\.com\/edit/ig) !== null) ||
        (parent && parent.location && parent.location.href == document.location.href);
}
catch (e) {
    console.log("[user-web] error checking for top frame: " + e.message);
    isTop = false;
}

if (isTop) {
    var userWeb = new function () {
        var me = this;
        var url = document.location.href;
        var $style = null;

        me.IsFeedly = document.location.href.match(/\/\/feedly\.com/i) != null;
        me.IsLinux = navigator.appVersion.indexOf("Linux") != -1;
        me.UserStyle = "";

        me.Debug = {
            LocalUrls: 0,
            UniqueUrls: 0,
            ShowEd: 0,
            Reloader: 0
        };

        if (document.location.href.match(/(localhost\:44).*\.htm/i) != null) {
            me.Debug = {
                LocalUrls: 1,
                UniqueUrls: 1,
                ShowEd: 1,
                Reloader: 1
            };
        }

        if (me.Debug.Reloader) {
            $(document).dblclick(function () {
                document.location.href = document.location.href;
            });
        }

        me.GetRoot = function () {
            return me.Debug.LocalUrls ? "https://localhost:44300/" : "https://user-web.googlecode.com/svn/trunk/";
        }

        me.Load = function () {
            if ($("#user-web-style").data("local") == 1) {
                me.Debug.LocalUrls = true;
                me.Debug.UniqueUrls = true;
                me.Debug.Reloader = true;
            }

            if (me.IsFeedly) {
                window.setTimeout(function () {
                    me.DoLoadUi();
                }, 2000);
            }
            else {
                me.DoLoadUi();
            }

            me.Log("page url", url);

            //me.LoadStyleSheet("jquery-ui-1.10.4.custom");
            //me.LoadStyleSheet("user-web", me.Debug.UniqueUrls);

            me.LoadUserStyle();
        };

        me.DoLoadUi = function () {
            me.Log("loading ui", url);
            var ui = new userWebUi(me);

            me.LoadUi();
        };

        me.LoadUserStyle = function () {

            var config = {
                bbc_news: { exp: /bbc\.co\.uk\/(news|sport|nature)/i },
                feedly: { exp: /\/\/feedly\.com/i },
                boing_boing: { exp: /boingxboing\.net/i },
                //gmail: { exp: /mail\.google\.com/i },
                google_maps: { exp: /maps\.google\.co/i },
                google_calendar: { exp: /google\.com\/calendar/i },
                google_search: { exp: /google\/(search|webhp)/i },
                wikipedia: { exp: /wikipedia\.org/i },
                //you_tube: { exp: /youtube\.com/i },
                guardian: { exp: /guardian\.co\.uk/i },
                independent: { exp: /independent\.co\.uk/i },
                //private_eye: { exp: /private-eye\.co\.uk/i },
                old_reader: { exp: /theoldreader\.com/i },
                pocket: { exp: /getpocket\.com/i },
                stack_overflow: { exp: /stackoverflow\.com/i },
                test: { exp: /(testlocal|testlive|testinject)\.htm/i }
            };

            for (var name in config) {
                var cfg = config[name];
                cfg.name = name;

                if (url.match(cfg.exp) != null) {
                    me.Log("matched url", cfg.exp);

                    me.CurrentConfig = cfg;

                    if (cfg.exp != "") {
                        me.LoadUserStyleSheet(name.replace(/_/ig, "-"));
                        break;
                    }
                }
            }
        };

        me.ToggleStyle = function () {
            if ($style == null || $style.attr("href") == null) {
                me.LoadUserStyle();
            }
            else {
                $style.attr("href", null);
            }
        };

        me.ReloadStyle = function () {
            me.LoadUserStyle();
        };

        me.LoadUserStyleSheet = function (name) {
            var unique = me.Debug.UniqueUrls ? new Date().valueOf() : 1;
            var url = me.GetRoot() + "Styles/" + name + ".css?" + unique;

            me.Log("inserting style", url);

            me.UserStyle = name + " " + url;
            $("#user-web-box").text(me.UserStyle);

            if ($style == null) {
                $style = $("<link rel='stylesheet' type='text/css' id='user-web-css'>");
                $('head').append($style);
            }

            $style.attr("href", url);
        };

        me.CreateElement = function (parent, tag, className, text) {
            var el = $("<" + tag + "></" + tag + ">");

            if (className != null) {
                el.addClass(className);
            }

            if (text != null) {
                el.text(text);
            }

            if (parent != null) {
                $(parent).append(el);
            }

            return el;
        };

        me.Log = function (text1, text2) {
            if (text2 != null) {
                if (text1.length < 20) {
                    text1 = text1 + Array(21 - text1.length).join(" ");
                }

                console.log("[user-web] " + text1 + ": " + text2);
            }
            else {
                console.log("[user-web] " + text1);
            }
        };
    };

    function userWebUi(userWeb) {
        var me = userWeb;

        me.LoadUi = function () {

            me.CreateButton();
            me.CreateEditor();

            if (me.Debug.ShowEd) {
                window.setTimeout(function () {
                    me.ShowEd();
                }, 100);
            }
        };

        me.KeyUp = function (e) {
            if (((e.keyCode == 223 && !userWeb.IsLinux) || (e.keyCode == 192 && userWeb.IsLinux)) && e.ctrlKey) {
                if (e.shiftKey) {
                    debugger;
                }

                me.ShowEd();
                $(".user-web-dialog").css("top", "100px")
            }
        };

        me.CreateButton = function () {
            var cb = me.CreateElement($("body"), "div", "user-web-btn");
            var cbl = me
                .CreateElement(cb, "a", "user-web-btn-link")
                .prop("href", document.location.href)
                .click(function (e) {
                    if (e.button != 2) {
                        return false;
                    }
                });

            userWeb.Log("creating button", cb.parent().length);

            $(document).bind("keyup.readr-show-ed", me.KeyUp);

            cb.mouseup(function (event) {
                switch (event.button) {
                    case 0:
                        doclick(event.ctrlKey); //chrome
                        return false;
                        break;
                    case 1:
                        if (document.all) { //IE
                            doclick(event.ctrlKey);
                        }
                        return false;
                        break;
                    // case 2: //right click
                    //    break;
                }
            });

            var doclick = function (ctrlKey) {
                if (me.Ed != null && me.Ed.dialog("isOpen")) {
                    me.HideEd();
                }
                else {
                    me.ShowEd();
                }
            };

            // cb.contextmenu(function () {
            //     return false;
            // });
        };

        me.ShowEd = function () {
            if (me.Ed == null) {
                me.CreateEditor();
            }

            me.Ed.dialog("open");
        };

        me.HideEd = function () {
            me.Ed.dialog("close");
        };

        me.CreateEditor = function () {

            var width = Math.min($(window).width(), 600);
            var url = document.location.href;

            var html =
                '<div id="user-web-ed">' +
                '  <div class="user-web-dialog-inner">' +
                '      <div class="user-web-row">' +
                '        <div class="overflow"><a href="' + url + '">' + url + '</a></div>' +
                '      </div>' +
                '      <div class="user-web-row">' +
                '        <div id="user-web-box"></div>' +
                '      </div>' +
                '      <div class="user-web-button-row">' +
                '        <input type="button" id="user-web-reload" value="Reload Style" />' +
                '        <input type="button" id="user-web-toggle" value="Toggle Style" />' +
                '        <input type="button" id="user-web-local" value="Use Local" />' +
                '      </div>' +
                '  </div>' +
                '</div>';

            var $content = $(html);
            $("body").prepend($content);
            me.EdContent = $content;

            me.Ed = $content
                .dialog({
                    autoOpen: false,
                    title: "User Web",
                    width: width,
                    minHeight: 50,
                    dialogClass: "user-web-dialog"
                });

            $("#user-web-toggle").click(function () {
                userWeb.ToggleStyle();
            });

            $("#user-web-reload").click(function () {
                userWeb.ReloadStyle();
            });

            $("#user-web-local").click(function () {
                me.Debug.LocalUrls = me.Debug.UniqueUrls = !me.Debug.LocalUrls;
                SetLocalButtonText();
                userWeb.ReloadStyle();
            });

            function SetLocalButtonText() {
                $("#user-web-local").val(me.Debug.LocalUrls ? "Use Web" : "Use Local");
            };

            SetLocalButtonText();

            $("#user-web-box").text(userWeb.UserStyle);
        };
    };

    $(document).ready(function () {
        userWeb.Load();
    });
}